package GUI;

import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;

import CommonGui.MultiLineCellRenderer;
import CommonGui.MyTableModel;
import CommonGui.Utils;
import DataObjects.ItemInOrder;
import DataObjects.OrderSearch;
import Messages.MessageGetItemsForOrder;
import Messages.MessageGetItemsForOrderReply;
import Messages.MessageGetOrders;
import Messages.MessageGetOrdersReply;
import Messages.MessageShowAllInventoryReply;

public class PfManageOrders extends JPanel {
	/**
	 * Manage and search orders window
	 * 
	 * @author Alex
	 * @since 20/01/2013
	 * 
	 */
	private MainMenu mainMenu;

	private JPanel mainPanel;
	private JPanel ordersPanel;
	private JPanel actionsPanel;
	private JPanel searchPanel;

	private JButton btnShowOrder;
	private JButton btnPrintOrder;
	private JButton btnCloseOrder;

	private JTable ordersTable;
	private MyTableModel dtm;

	private Vector<Vector> ordersList;
	private Vector<String> ordersTableHeaders;

	public PfManageOrders(MainMenu mm) {
		super();
		this.mainMenu = mm;
		initialize();
	}

	private void initialize() {
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		add(getSearchPanel());
		add(getMainPanel());
		this.setAlignmentY(TOP_ALIGNMENT);
	}

	private JPanel getMainPanel() {
		this.mainPanel = new JPanel();
		this.mainPanel
				.setLayout(new BoxLayout(this.mainPanel, BoxLayout.X_AXIS));
		this.mainPanel.setAlignmentY(TOP_ALIGNMENT);
		this.mainPanel.setBorder(new EmptyBorder(5, 5, 5, 5));

		this.mainPanel.add(getOrdersPanel());
		this.mainPanel.add(getActionsPanel());
		// this.mainPanel.add(getSearchPanel());

		return this.mainPanel;
	}

	private JPanel getOrdersPanel() {
		this.ordersPanel = new JPanel();
		this.ordersTable = new JTable();

		OrderSearch srch = new OrderSearch();
		srch.limit = 100;
		srch.itemName = "";
		srch.supplierName = "";
		MessageGetOrders msgOrders = new MessageGetOrders(srch);
		try {
			mainMenu.ms.client.sendToServer(msgOrders);
			MessageGetOrdersReply result = (MessageGetOrdersReply) mainMenu.ms.client
					.GetMessage();
			this.ordersList = result.getOrders();
			System.out.println("Orders count: " + ordersList.size());
			System.out.println("Search object: \n" + srch);

			for (int i = 0; i < ordersList.size(); i++) {
				System.out.println("Order No: " + i);
				for (int j = 0; j < ordersList.get(i).size(); j++) {

					System.out.println(j + ") " + ordersList.get(i).get(j));
					System.out.println("");
				}

			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		this.ordersTableHeaders = new Vector<String>();
		ordersTableHeaders.add("מס. הזמנה");
		ordersTableHeaders.add("ספק");
		ordersTableHeaders.add("יום הנפקה");
		ordersTableHeaders.add("שעת הנפקה");
		ordersTableHeaders.add("סטטוס");
		ordersTableHeaders.add("פריטים");

		this.ordersPanel.setBorder(new TitledBorder(UIManager
				.getBorder("TitleBorder.border"), "הזמנות",
				TitledBorder.CENTER, TitledBorder.TOP, null, null));
		this.ordersPanel.setLayout(new BoxLayout(this.ordersPanel,
				BoxLayout.Y_AXIS));
		// this.ordersPanel.setPreferredSize(new Dimension(100,200));
		// this.ordersPanel.setMinimumSize(new Dimension(100,200));
		// this.ordersPanel.setMaximumSize(new Dimension(100,200));
		this.ordersPanel.setAlignmentY(TOP_ALIGNMENT);

		this.dtm = new MyTableModel(this.ordersList, ordersTableHeaders);

		this.ordersTable.setModel(dtm);

		ordersTable.setDefaultRenderer(Object.class,
				new MultiLineCellRenderer());
		ordersTable.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
		ordersTable.setFont(new Font("David", Font.BOLD, 16));
		ordersTable.getTableHeader().setFont(new Font("Arial", Font.BOLD, 17));
		ordersTable.getTableHeader().setBackground(new Color(173, 216, 230));
		ordersTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		ordersTable.setRowHeight(30);
		ordersTable.setFillsViewportHeight(true);
		ordersTable.setGridColor(new Color(25, 25, 112));
		ordersTable.setBackground(new Color(224, 255, 255));
		ordersTable.setForeground(new Color(0, 0, 0));
		ordersTable.setAutoCreateRowSorter(true);
		Utils.updateRowHeights(ordersTable);
		this.ordersTable
				.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

		for (int i = 0; i < ordersTable.getColumnModel().getColumnCount(); i++) {

		}
		int[] cols = { 3,4, 5 };
		Utils.hideColumns(ordersTable, cols);

		ordersTable.addMouseListener(new MouseAdapter() {
			   public void mouseClicked(MouseEvent e10) {
			     if (e10.getClickCount() == 1) {
			       JTable target = (JTable)e10.getSource();
			       int row = target.getSelectedRow();
			       int column = target.getSelectedColumn();

			       if(row!=-1)
			     {
				       if (e10.getClickCount() == 2 && row!=-1){
				    	   Vector<String> order = (Vector<String>) ((MyTableModel) ordersTable
									.getModel()).getDataVector().get(
									ordersTable.convertRowIndexToModel(ordersTable
											.getSelectedRow()));
							int id = Integer.parseInt(order.get(0));
							
							
							
							MessageGetItemsForOrder msg = new MessageGetItemsForOrder(id);
							try {
								mainMenu.ms.client.sendToServer(msg);
								MessageGetItemsForOrderReply resp = (MessageGetItemsForOrderReply)mainMenu.ms.client.GetMessage();
								Vector<Vector> items = resp.getOrders();
								ArrayList<ItemInOrder> data = new ArrayList<ItemInOrder>();
								float total = 0;
								
								for(int i = 0; i < items.size(); i++){
									ItemInOrder item = new ItemInOrder();
									item.setItemName(items.get(i).get(0).toString());
									item.setAmount(Float.parseFloat(items.get(i).get(1).toString()));
									item.setPrice(Float.parseFloat(items.get(i).get(2).toString()));
									item.setDate(items.get(i).get(3).toString());
									item.setTime(items.get(i).get(4).toString());
									item.setSupplier_name(items.get(i).get(5).toString());
									item.setPhone(items.get(i).get(6).toString());
									item.setAdress(items.get(i).get(7).toString() + ", " + items.get(i).get(8).toString() + ", " + items.get(i).get(9).toString());
									item.setOrderId(items.get(i).get(10).toString());
									total += item.getPrice() * item.getAmount();
									data.add(item);
								}
								
								HashMap params = new HashMap();
								params.put("Total", total);
								JRBeanCollectionDataSource reportData = new JRBeanCollectionDataSource(data);
								JasperPrint print;
								try {
									print = JasperFillManager.fillReport("Reports/Orders/Order.jasper", params, reportData);
									JasperViewer.viewReport(print, false);
								} catch (JRException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
								
							} catch (IOException e2) {
								// TODO Auto-generated catch block
								e2.printStackTrace();
					         }
			       }
			     }
			     
			    
			     
			     }}
			   
			 });
		ordersPanel.add(new JScrollPane(ordersTable));

		return this.ordersPanel;
	}

	private JPanel getActionsPanel() {
		actionsPanel = new JPanel();
		actionsPanel.setLayout(new BoxLayout(this.actionsPanel,
				BoxLayout.Y_AXIS));
		actionsPanel.setBorder(new TitledBorder(UIManager
				.getBorder("TitleBorder.border"), "פעולות",
				TitledBorder.CENTER, TitledBorder.TOP, null, null));

		//this.btnShowOrder = new JButton("הצג הזמנה");
		this.btnPrintOrder = new JButton("הצג הזנמה");
	//	this.btnCloseOrder = new JButton("סגור הזמנה");

		this.btnPrintOrder.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 1) {
					Vector<String> order = (Vector<String>) ((MyTableModel) ordersTable
							.getModel()).getDataVector().get(
							ordersTable.convertRowIndexToModel(ordersTable
									.getSelectedRow()));
					int id = Integer.parseInt(order.get(0));
					
					
					
					MessageGetItemsForOrder msg = new MessageGetItemsForOrder(id);
					try {
						mainMenu.ms.client.sendToServer(msg);
						MessageGetItemsForOrderReply resp = (MessageGetItemsForOrderReply)mainMenu.ms.client.GetMessage();
						Vector<Vector> items = resp.getOrders();
						ArrayList<ItemInOrder> data = new ArrayList<ItemInOrder>();
						float total = 0;
						
						for(int i = 0; i < items.size(); i++){
							ItemInOrder item = new ItemInOrder();
							item.setItemName(items.get(i).get(0).toString());
							item.setAmount(Float.parseFloat(items.get(i).get(1).toString()));
							item.setPrice(Float.parseFloat(items.get(i).get(2).toString()));
							item.setDate(items.get(i).get(3).toString());
							item.setTime(items.get(i).get(4).toString());
							item.setSupplier_name(items.get(i).get(5).toString());
							item.setPhone(items.get(i).get(6).toString());
							item.setAdress(items.get(i).get(7).toString() + ", " + items.get(i).get(8).toString() + ", " + items.get(i).get(9).toString());
							item.setOrderId(items.get(i).get(10).toString());
							total += item.getPrice() * item.getAmount();
							data.add(item);
						}
						
						HashMap params = new HashMap();
						params.put("Total", total);
						JRBeanCollectionDataSource reportData = new JRBeanCollectionDataSource(data);
						JasperPrint print = JasperFillManager.fillReport("Reports/Orders/Order.jasper", params, reportData);
						JasperViewer.viewReport(print, false);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (JRException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					
				}
			}
		});

		//actionsPanel.add(this.btnShowOrder);
		//actionsPanel.add(Box.createHorizontalGlue());
		actionsPanel.add(this.btnPrintOrder);
		//actionsPanel.add(Box.createHorizontalGlue());
		//actionsPanel.add(this.btnCloseOrder);
		//actionsPanel.add(Box.createHorizontalGlue());

		actionsPanel.setMaximumSize(new Dimension(100, 100));
		// actionsPanel.setMaximumSize(new Dimension(10, 10));
		// actionsPanel.setPreferredSize(new Dimension(10,10));
		actionsPanel.setAlignmentY(TOP_ALIGNMENT);

		return actionsPanel;
	}

	private JPanel getSearchPanel() {
		this.searchPanel = new JPanel();
		this.searchPanel.setLayout(new BoxLayout(this.searchPanel,
				BoxLayout.X_AXIS));
		JLabel label=new JLabel("תעודות הזמנה");
		label.setFont(new Font("Tahoma", Font.BOLD, 25));
		
		
		
		//this.searchPanel.setBorder(new TitledBorder(UIManager
		//		.getBorder("TitleBorder.border"), "חיפוש \\ סינון",
		//		TitledBorder.CENTER, TitledBorder.TOP, null, null));
		// searchPanel.setMinimumSize(new Dimension(800,50));
		// searchPanel.setMaximumSize(new Dimension(800,50));
		// searchPanel.setPreferredSize(new Dimension(800,50));
		this.searchPanel.add(label);
		

		return this.searchPanel;
	}

	/*
	 * Update rows heights of table in case we have multiline cells in it
	 * 
	 * @author Alex
	 * 
	 * @since 20/01/2013
	 */

}
